<template>
    <div>
        <div id="logIcon">
            <span @click="logShow = !logShow">LOG</span>
            <span @click="onClear" style="margin-left: 10px; color: red">CLS</span>
        </div>
        <div v-show="logShow">
            <pre id="log" ref="log"/>
        </div>
    </div>

</template>

<script>
    export default {
        name: "Log",
        data() {
            return {
                logShow: false
            }
        },
        mounted() {
            const self = this;
            const c = this.$refs.log;
            window.log = function () {
                for (let arg of arguments) {
                    let div = document.createElement('div');
                    div.innerHTML = self.syntaxHighlight(arg);
                    c.appendChild(div);
                }

                c.appendChild(document.createElement('hr'));
                c.scrollTop = c.scrollHeight;
            }
        },
        methods: {
            syntaxHighlight(json) {
                if (typeof json != 'string') {
                    json = JSON.stringify(json, undefined, 2);
                }
                json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                    var cls = 'number';
                    if (/^"/.test(match)) {
                        if (/:$/.test(match)) {
                            cls = 'key';
                        } else {
                            cls = 'string';
                        }
                    } else if (/true|false/.test(match)) {
                        cls = 'boolean';
                    } else if (/null/.test(match)) {
                        cls = 'null';
                    }
                    return '<span class="' + cls + '">' + match + '</span>';
                });
            },

            onClear() {
                this.$refs.log.innerHTML = '';
            },
        },
    }
</script>

<style>
    #logIcon {
        background: #dadada;
        position: fixed;
        left: 0;
        bottom: 0;
        z-index: 10000;
        padding: .2rem .7rem;
        border: 1px solid #999;
        font-size: .4rem;
    }

    #log {
        height: 10rem;
        width: 100%;
        background: #deebe5;
        position: fixed;
        z-index: 9999;
        bottom: 0;
        overflow: auto;
        padding: 1rem .3rem;
    }

    #log pre {
        outline: 1px solid #ccc;
        padding: 5px;
        margin: 5px;
    }

    #log .string {
        color: green;
    }

    #log .number {
        color: darkorange;
    }

    #log .boolean {
        color: blue;
    }

    #log .null {
        color: magenta;
    }

    #log .key {
        color: red;
    }
</style>
